package controllers

import (
	"fmt"
	"net/http"

	"github.com/diogoxiang/smock/database"
	"github.com/diogoxiang/smock/models"
	"github.com/gin-gonic/gin"
)

// GetAllMockAPIs 获取所有Mock API
func GetAllMockAPIs(c *gin.Context) {
	var mockAPIs []models.MockAPI

	// 获取查询参数
	query := c.Query("query")
	group := c.Query("group")

	db := database.DB.Preload("Responses").Preload("Rules")

	// 如果有搜索关键词，添加搜索条件
	if query != "" {
		db = db.Where("name LIKE ? OR path LIKE ? OR description LIKE ?", "%"+query+"%", "%"+query+"%", "%"+query+"%")
	}

	// 如果有分组筛选，添加分组条件
	if group != "" {
		db = db.Where("group_name = ?", group)
	}

	result := db.Find(&mockAPIs)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
		return
	}
	c.JSON(http.StatusOK, mockAPIs)
}

// GetMockAPI 获取单个Mock API
func GetMockAPI(c *gin.Context) {
	id := c.Param("id")
	var mockAPI models.MockAPI
	result := database.DB.Preload("Responses").Preload("Rules").First(&mockAPI, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Mock API not found"})
		return
	}
	c.JSON(http.StatusOK, mockAPI)
}

// CreateMockAPI 创建新的Mock API
func CreateMockAPI(c *gin.Context) {
	var mockAPI models.MockAPI
	if err := c.ShouldBindJSON(&mockAPI); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	result := database.DB.Create(&mockAPI)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
		return
	}
	c.JSON(http.StatusCreated, mockAPI)
}

// UpdateMockAPI 更新Mock API
func UpdateMockAPI(c *gin.Context) {
	id := c.Param("id")
	var mockAPI models.MockAPI
	if err := database.DB.Preload("Responses").Preload("Rules").First(&mockAPI, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Mock API not found"})
		return
	}

	var updatedMockAPI models.MockAPI
	if err := c.ShouldBindJSON(&updatedMockAPI); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 更新基本信息
	mockAPI.Name = updatedMockAPI.Name
	mockAPI.Path = updatedMockAPI.Path
	mockAPI.Method = updatedMockAPI.Method
	mockAPI.Description = updatedMockAPI.Description
	mockAPI.GroupName = updatedMockAPI.GroupName
	mockAPI.Prefix = updatedMockAPI.Prefix

	if err := database.DB.Save(&mockAPI).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, mockAPI)
}

// DeleteMockAPI 删除Mock API
func DeleteMockAPI(c *gin.Context) {
	id := c.Param("id")
	var mockAPI models.MockAPI
	if err := database.DB.First(&mockAPI, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Mock API not found"})
		return
	}

	// 删除关联的响应和规则
	database.DB.Where("mock_api_id = ?", id).Delete(&models.MockResponse{})
	database.DB.Where("mock_api_id = ?", id).Delete(&models.MatchRule{})

	// 删除API
	database.DB.Delete(&mockAPI)

	c.JSON(http.StatusOK, gin.H{"message": "Mock API deleted successfully"})
}

// GetAllGroups 获取所有API分组
func GetAllGroups(c *gin.Context) {
	var groups []struct {
		GroupName string `json:"group_name"`
		Prefix    string `json:"prefix"`
	}

	result := database.DB.Model(&models.MockAPI{}).Select("DISTINCT group_name, prefix").Find(&groups)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error.Error()})
		return
	}

	c.JSON(http.StatusOK, groups)
}

// ImportAPIs 导入API配置
func ImportAPIs(c *gin.Context) {
	var importData struct {
		APIs []models.MockAPI `json:"apis"`
	}

	if err := c.ShouldBindJSON(&importData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid import data format: " + err.Error()})
		return
	}

	tx := database.DB.Begin()
	for i := range importData.APIs {
		// 清除ID以避免冲突
		importData.APIs[i].ID = 0
		for j := range importData.APIs[i].Responses {
			importData.APIs[i].Responses[j].ID = 0
			importData.APIs[i].Responses[j].MockAPIID = 0
		}
		for j := range importData.APIs[i].Rules {
			importData.APIs[i].Rules[j].ID = 0
			importData.APIs[i].Rules[j].MockAPIID = 0
		}

		if err := tx.Create(&importData.APIs[i]).Error; err != nil {
			tx.Rollback()
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to import APIs: " + err.Error()})
			return
		}
	}
	tx.Commit()

	c.JSON(http.StatusOK, gin.H{"message": "Successfully imported " + fmt.Sprintf("%d", len(importData.APIs)) + " APIs"})
}
